/**
 * Copyright (C) 2018-2020
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.user.service.mapper;

import co.yixiang.common.mapper.CoreMapper;
import co.yixiang.modules.user.domain.YxDistributorRelation;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.service.dto.PromUserDto;
import co.yixiang.modules.user.service.dto.YxUserDto;
import co.yixiang.modules.user.service.dto.YxUserQueryCriteria;
import co.yixiang.modules.user.service.dto.ZFDataDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
* @author hupeng
* @date 2020-05-12
*/
@Repository
public interface UserMapper extends CoreMapper<YxUser> {


    @Select("<script>SELECT u.uid,u.nickname,u.avatar,DATE_FORMAT(u.create_time,'%Y/%m/%d') as time," +
            "u.spread_count as childCount,COUNT(o.id) as orderCount," +
            "IFNULL(SUM(o.pay_price),0) as numberCount FROM yx_user u " +
            "LEFT JOIN yx_store_order o ON u.uid=o.uid " +
            "WHERE u.uid in <foreach item='id' index='index' collection='uids' " +
            " open='(' separator=',' close=')'>" +
            "   #{id}" +
            " </foreach> <if test='keyword != null'>" +
            " AND ( u.nickname LIKE CONCAT(CONCAT('%',#{keyword}),'%') OR u.phone LIKE CONCAT(CONCAT('%',#{keyword}),'%'))</if>" +
            " GROUP BY u.uid ORDER BY #{orderByStr} " +
            "</script>")
    List<PromUserDto> getUserSpreadCountList(Page page,
                                             @Param("uids") List uids,
                                             @Param("keyword") String keyword,
                                             @Param("orderByStr") String orderBy);

    @Update("update yx_user set now_money=now_money-#{payPrice}" +
            " where uid=#{uid}")
    int decPrice(@Param("payPrice") BigDecimal payPrice, @Param("uid") Long uid);
//
//    @Update("update yx_user set brokerage_price=brokerage_price+#{brokeragePrice}" +
//            " where uid=#{uid}")
//    int incBrokeragePrice(@Param("brokeragePrice") double brokeragePrice,@Param("uid") int uid);

    @Update("update yx_user set pay_count=pay_count+1" +
            " where uid=#{uid}")
    int incPayCount(@Param("uid") Long uid);

    @Update("update yx_user set now_money=now_money+#{price}" +
            " where uid=#{uid}")
    int incMoney(@Param("uid") Long uid,BigDecimal price);

    @Update("update yx_user set integral=integral-#{integral}" +
            " where uid=#{uid}")
    int decIntegral(@Param("integral") double integral,@Param("uid") Long uid);

    @Update("update yx_user set integral=integral+#{integral}" +
            " where uid=#{uid}")
    int incIntegral(@Param("integral") double integral,@Param("uid") Long uid);

    @Update( "update yx_user set status = #{status} where uid = #{id}")
    void updateOnstatus(@Param("status") Integer status, @Param("id") Long id);

    @Update( "update yx_user set is_freeze = #{isFreeze} where uid = #{id}")
    void updateOnstatus1(@Param("isFreeze") Integer isFreeze, @Param("id") Long id);

    @Update( "update yx_user set now_money = now_money + ${money} where uid = #{id}")
    void updateMoney(@Param("money") double money, @Param("id") long id);

    @Update("update yx_user set brokerage_price = brokerage_price+ ${price} where uid = #{id}")
    void incBrokeragePrice(@Param("price") BigDecimal price,@Param("id") Long id);

    @Select("select * from yx_user where my_code = #{referralCode}")
    YxUser selectByReferralCode(String referralCode);

    @Select("SELECT a.* , (SELECT b.create_time from yx_distributor_relation b where uid = a.uid) as time from yx_user a where uid in (SELECT uid from yx_distributor_relation where p_uid = #{uid})")
    List<PromUserDto> getOneGradeUser(@Param("uid") Long uid);

    @Select("SELECT a.* , (SELECT b.create_time from yx_distributor_relation b where uid = a.uid) as time from yx_user a where uid in (SELECT uid from yx_distributor_relation where p_uid in (SELECT uid from yx_distributor_relation where p_uid = #{uid}))")
    List<PromUserDto> getTwoGradeUser(@Param("uid") Long uid);

    @Update("update yx_user set now_money = now_money+ ${price} where uid = #{uid}")
    void incNowPrice(@Param("price") BigDecimal price,@Param("uid") Long uid);

    @Select("SELECT a.* , (SELECT b.create_time from yx_distributor_relation b where uid = a.uid) as time from yx_user a where uid in (SELECT p_uid from yx_distributor_relation where uid = #{uid})")
    List<PromUserDto> pSpread(@Param("uid")Long uid);

    @Select("select * from yx_distributor_relation where p_uid=#{uid}")
    List<YxDistributorRelation> selectAllSonPeople(@Param("uid") Long uid);

    @Select("select sum(price) from yx_distributor_earnings where d_uid in ( ${uid} ) and status=1 and is_over=1")
    BigDecimal selectAllMoney(@Param("uid") String uid);

    @Select("<script> SELECT yu.* , IFNULL(yac.real_name,yu.nickname) as realName1 from yx_user yu " +
            " LEFT JOIN yx_authentication yac on yu.uid = yac.uid " +
            " where 1 = 1 and logout_account = 0" +
            " <if test=\"phone != null and phone != ''\"> and yu.phone  like CONCAT('%',#{phone},'%')  </if> " +
            " <if test=\"nickname != null and nickname != ''\"> and yac.real_name  like CONCAT('%',#{nickname},'%')  </if> </script> ")
    List<YxUserDto> selectUserList( YxUserQueryCriteria criteria);

    @Update(" UPDATE yx_auction_user_log set is_success = 1 where uid = #{uid} and TO_DAYS(auction_time) = TO_DAYS(now()) ")
    void updateUserLog(@Param("uid") Long uid);

    @Update(" update yx_user set now_money = #{balance} , data_version = data_version + 1 where uid = #{uid} " +
            " and data_version = #{dataVersion} ")
    Integer updateUserPriceById(@Param("uid") Long uid,@Param("dataVersion") Integer dataVersion,@Param("balance")  BigDecimal balance);

    @Select(" SELECT * from yx_user where uid in ( SELECT uid from yx_distributor_relation where p_uid = 1 ) ")
    List<Map<String , Object>> zsUser();

    @Select("<script> SELECT COUNT(1) from yx_auction_order where user_id in ( ${uidStr} ) and `status` != 5 " +
            " <if test=\"type == '1'.toString\"> and TO_DAYS(create_time) = TO_DAYS(now())  </if> </script>")
    Integer getAuctionNum(@Param("uidStr") String uidStr ,  @Param("type") Integer type);

    @Select("<script> SELECT IFNULL(sum(price),0) from yx_auction_order where user_id in ( ${uidStr} ) and `status` != 5 " +
            " <if test=\"type == '1'.toString\"> and TO_DAYS(create_time) = TO_DAYS(now())  </if> </script>")
    BigDecimal getAuctionPrice(@Param("uidStr") String uidStr ,  @Param("type") Integer type);

    @Select("<script> SELECT IFNULL(SUM(price),0) from yx_distributor_earnings where uid in ( ${uidStr} )  " +
            " <if test=\"type == '1'.toString\"> and TO_DAYS(create_time) = TO_DAYS(now())  </if> </script>")
    BigDecimal getAuctionBro(@Param("uidStr") String uidStr ,  @Param("type") Integer type);

    @Select(" SELECT COUNT(1) from yx_user where now_level = #{level} and uid in ( ${uidStr} )  ")
    Integer getUserByLevel(@Param("uidStr") String uidStr , @Param("level") Integer level);


    @Select(" SELECT yub.* , IFNULL(ya.real_name,yu.nickname) as realName , yu.phone as phone from yx_user_bill yub " +
            " LEFT JOIN yx_user yu on yub.uid = yu.uid " +
            " LEFT JOIN yx_authentication ya on ya.uid = yub.uid" +
            " where yub.title = '开通会员' ORDER BY yub.create_time desc ")
    List<Map<String, Object>> getOpenUserData();

    @Select(" SELECT yui.weixin_name as wxName , yui.weixin_account as wxAccount , yui.weixin_code as wxCode ,\n" +
            " yui.zhifubao_name as zfbName , yui.zhifubao_account as zfbAccount , yui.zhifubao_code as zfbCode,\n" +
            " yub.bank_name as yhName , yub.bank_number as yhNumber , yub.image as yhCode , yub.real_name as yhRealName \n" +
            " from yx_userinfo yui LEFT JOIN yx_user_bank yub on yui.uid = yub.uid where yui.uid = #{uid}  ")
    ZFDataDto getZfData(Long uid);


    @Select(" SELECT uid FROM yx_distributor_relation where p_uid in ( #{uid} ) " +
            " UNION " +
            " SELECT uid FROM yx_distributor_relation where p_uid in ( SELECT uid from yx_distributor_relation where p_uid = #{uid} ) ")
    List<Long> selectRelation(@Param("uid") Long uid);

    @Select(" SELECT IFNULL(SUM(price),0) from yx_auction_order where user_id in ( ${uid} )  and `status` != 5  and TO_DAYS(create_time) = TO_DAYS(now()) ")
    BigDecimal selectAllNowMoney(@Param("uid") String uid);

    @Select(" SELECT COUNT(1) from yx_auction_order where user_id in ( ${uid} ) and `status` != 5 and TO_DAYS(create_time) = TO_DAYS(NOW()) ")
    Integer selectTeamCount(@Param("uid") String uid);
}
